package com.freak.wanandroid.model.discover.tab;

import android.content.Intent;
import android.view.View;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import com.freak.wanandroid.R;
import com.freak.wanandroid.base.fragment.BaseLifecycleFragment;
import com.freak.wanandroid.bean.ArticleListBean;
import com.freak.wanandroid.model.discover.DiscoverViewModel;
import com.freak.wanandroid.model.home.activity.ArticleDetailAct;
import com.freak.wanandroid.model.home.adapter.HomePageAdapter;
import com.freak.wanandroid.model.login.LoginActivity;
import com.freak.wanandroid.net.CommonLiveData;
import com.freak.wanandroid.util.ToastUtil;
import com.freak.wanandroid.util.ToolUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * 最新项目
 *
 * @author: freak
 * @date: 2022/9/25
 */
public class LatestProjectFragment extends BaseLifecycleFragment<DiscoverViewModel> {
    private RecyclerView mRecycleViewHome;

    private SwipeRefreshLayout mSwipeRefreshLayoutArticle;

    private HomePageAdapter mHomePageAdapter;

    private List<ArticleListBean.Datas> mList;

    private int mCurPage = 1;

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_lastest_project;
    }

    @Override
    protected void initEventAndData(View view) {
        initTheLatestProject(view);
    }

    @Override
    protected void onResumeLoadData() {
        mViewModel.getArticle(String.valueOf(mCurPage));
    }

    @Override
    protected void dataObserver() {
        mViewModel.mDoCollect.observe(this, this::doCollectSuccessOrError);
        mViewModel.mDoCancelCollect.observe(this, this::doCancelCollectSuccessOrError);
        mViewModel.mGetArticle.observe(this, this::getArticleSuccess);
        mViewModel.mGetArticleError.observe(this, this::getArticleError);
    }

    /**
     * 最新项目
     *
     * @param view View
     */
    private void initTheLatestProject(View view) {
        mList = new ArrayList<>();
        mRecycleViewHome = view.findViewById(R.id.home_recycle);
        mSwipeRefreshLayoutArticle = view.findViewById(R.id.swipeRefreshLayoutArticle);
        mRecycleViewHome.setLayoutManager(new LinearLayoutManager(mCurrentActivity));
        mHomePageAdapter = new HomePageAdapter(R.layout.item_homepage, mList);
        mHomePageAdapter.bindToRecyclerView(mRecycleViewHome);
        mHomePageAdapter.setOnItemClickListener((baseQuickAdapter, view1, i) -> {
            ArticleListBean.Datas data = mList.get(i);
            switch (view1.getId()) {
                case R.id.home_item_collect:
                    if (ToolUtils.isLogin(mContext)) {
                        if (data.getCollect()) {
                            mViewModel.doCancelCollect(data.getId());
                        } else {
                            mViewModel.doCollect(data.getId());
                        }
                        showLoading();
                    } else {
                        ToastUtil.showShort(mContext, "请先登录");
                    }
                    break;
                case R.id.ll_item:
                    Intent intent = new Intent(getActivity(), ArticleDetailAct.class);
                    intent.putExtra("url", data.getLink());
                    intent.putExtra("title", data.getTitle());
                    startActivity(intent);
                    break;
            }

        });
        mHomePageAdapter.disableLoadMoreIfNotFullPage();
        mHomePageAdapter.setOnLoadMoreListener(() -> {
            mCurPage++;
            mViewModel.getArticle(String.valueOf(mCurPage));
            showLoading();
        }, mRecycleViewHome);
        mHomePageAdapter.setEmptyView(R.layout.include_no_data, mRecycleViewHome);
        mSwipeRefreshLayoutArticle.setOnRefreshListener(() -> {
            mCurPage = 1;
            mViewModel.getArticle(String.valueOf(mCurPage));
            showLoading();
        });
        mRecycleViewHome.setAdapter(mHomePageAdapter);
    }

    /**
     * 收藏成功或失败处理
     *
     * @param commonLiveData CommonLiveData
     */
    public void doCollectSuccessOrError(CommonLiveData commonLiveData) {
        dismissLoading();
        if (CommonLiveData.SUCCESS == commonLiveData.code) {
            mCurPage = 1;
            mViewModel.getArticle(String.valueOf(mCurPage));
            showLoading();
            ToastUtil.showShort(getActivity(), "收藏成功");
            return;
        }
        ToastUtil.showShort(getActivity(), "登录过期，请重新登录");
        ToolUtils.logout(getActivity());
        LoginActivity.startAction(getActivity());
    }

    /**
     * 获取文章成功回调
     *
     * @param articleListBean ArticleListBean
     */
    public void getArticleSuccess(ArticleListBean articleListBean) {
        mSwipeRefreshLayoutArticle.setRefreshing(false);
        dismissLoading();
        if (mCurPage == 1) {
            mList.clear();
        }
        mList.addAll(articleListBean.getDatas());
        if (mCurPage >= articleListBean.getPageCount()) {
            mHomePageAdapter.loadMoreEnd();
        } else {
            mHomePageAdapter.loadMoreComplete();
        }
        mHomePageAdapter.setNewData(mList);
    }


    public void getArticleError(String msg) {
        dismissLoading();
        mRecycleViewHome.setVisibility(View.GONE);
    }

    public void doCancelCollectSuccessOrError(CommonLiveData commonLiveData) {
        dismissLoading();
        if (CommonLiveData.SUCCESS == commonLiveData.code) {
            mCurPage = 1;
            mViewModel.getArticle(String.valueOf(mCurPage));
            showLoading();
            ToastUtil.showShort(getActivity(), "取消收藏成功");
            return;
        }
        ToastUtil.showShort(getActivity(), "登录过期，请重新登录");
        ToolUtils.logout(getActivity());
        LoginActivity.startAction(getActivity());
    }

}
